package controller;

import model.Counter;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@WebServlet("/Rank")
public class RankServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 负责按用户猜数次数对记录进行升序排列
        ServletContext application = request.getServletContext();
        Counter counter = (Counter) application.getAttribute("counter");
        if (counter == null){
            counter = new Counter();
            application.setAttribute("counter", counter);
        }

        // 获取排序后的记录
        List<Map.Entry<String, Integer>> list = counter.sort();
        request.setAttribute("list", list);

        // 跳转到排行榜页面
        RequestDispatcher view = request.getRequestDispatcher(response.encodeURL("rank.jsp"));
        view.forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
